// 封装购物车模块
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'
import { insertCartAPI, getCartListAPI, delCartAPI } from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
  // 1. 定义state - cartList
  const cartList = ref([])
  
  // 判断用户是否登录
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo?.token)
   
  // 加入购物车
  const addCart = async (goods) => {
    if (isLogin.value) {
      const { skuId, count } = goods
      // 加入购物车接口
      await insertCartAPI({skuId, count})
      // 获取购物车列表接口
      updateCart()
    } else {
      // 添加购物车操作
      // 已添加过 - count + 1
      // 没有添加过 - 直接push
      // 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if (item) {
        // 找到了
        item.count += goods.count
      } else {
        // 没找到
        cartList.value.push(goods)
      }
    }
  }

  // 删除购物车
  const delCart = async (skuId) => {
    if (isLogin.value) {
      await delCartAPI([skuId])
      updateCart()
    } else {
      // 思路：
      // 1. 找到要删除项的下标值 - splice
      // 2. 使用数组的过滤方法 - filter
      const idx = cartList.value.findIndex((item) => skuId === item.skuId)
      cartList.value.splice(idx, 1)
    }
  }

  // 清空本地购物车
  const clearCartlist = () => {
    cartList.value = []
  }

  // 更新购物车
  const updateCart = async () => {
    const res = await getCartListAPI()
    cartList.value = res.result
  }

  // 单选功能
  const singleCheck = (skuId, selected) => {
    // 通过skuId找到要修改的那一项 然后把它的selected修改为传过来的selected
    const item = cartList.value.find((item) => item.skuId === skuId)
    item.selected = selected
  }

  // 全选功能
  const allCheck = (selected) => {
    cartList.value.forEach(item => {
      item.selected = selected
    })
  }

  // 计算属性
  const allCount = computed(() => cartList.value.reduce((a,c) => a + c.count, 0))
  const allPrice = computed(() => cartList.value.reduce((a,c) => a + c.count * c.price, 0))
  // 全选
  const isAll = computed(() => cartList.value.every((item) => item.selected))
  // 选择商品属性
  const selectedCount = computed(() => cartList.value.reduce((a,c) => {
    if(c.selected){
      return a + c.count
    } else return a
  }, 0))
  const selectedPrice = computed(() => cartList.value.reduce((a,c) => {
    if(c.selected){
      return a + c.count * c.price
    } else return a
  }, 0))

  return {
    cartList,
    allCount,
    allPrice,
    isAll,
    selectedCount,
    selectedPrice,
    addCart,
    delCart,
    clearCartlist,
    singleCheck,
    allCheck,
    updateCart
  }
}, {
  persist: true,
})